

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/blog/img/fluid.png">
  <link rel="icon" href="/blog/images/base.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Airfe">
  <meta name="keywords" content="">
  
    <meta name="description" content="本文将介绍前端请求的一些技术。">
<meta property="og:type" content="article">
<meta property="og:title" content="Ajax">
<meta property="og:url" content="https://airfe.gitee.io/blog/2023/06/17/Ajax/index.html">
<meta property="og:site_name" content="Airfe的博客">
<meta property="og:description" content="本文将介绍前端请求的一些技术。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://markdown-1307246189.cos.ap-chongqing.myqcloud.com/%20markdown/image-20230616104425111.png">
<meta property="article:published_time" content="2023-06-17T00:00:00.000Z">
<meta property="article:modified_time" content="2024-04-01T01:55:13.628Z">
<meta property="article:author" content="Airfe">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://markdown-1307246189.cos.ap-chongqing.myqcloud.com/%20markdown/image-20230616104425111.png">
  
  
  
    <meta name="referrer" content="no-referrer" />
  
  <title>Ajax - Airfe的博客</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/blog/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/blog/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/blog/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"airfe.gitee.io","root":"/blog/","version":"1.9.4","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":true,"baidu":"699a5d71ac7179b23874a59b0666a6f6","google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":"RW68dMkEpeIOJJiBr1lPkhOS-gzGzoHsz","app_key":"P5fzMTGSJIoTaGvmgzsUHeNZ","server_url":"https://rw68dmke.lc-cn-n1-shared.com","path":"window.location.pathname","ignore_local":false}},"search_path":"/blog/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/blog/js/utils.js" ></script>
  <script  src="/blog/js/color-schema.js" ></script>
  

  
    <!-- Baidu Analytics -->
    <script async>
      if (!Fluid.ctx.dnt) {
        var _hmt = _hmt || [];
        (function() {
          var hm = document.createElement("script");
          hm.src = "https://hm.baidu.com/hm.js?699a5d71ac7179b23874a59b0666a6f6";
          var s = document.getElementsByTagName("script")[0];
          s.parentNode.insertBefore(hm, s);
        })();
      }
    </script>
  

  

  

  

  

  

  
    
  



  
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/blog/">
      <strong>Airfe</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/about/">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/links/">
                <i class="iconfont icon-link-fill"></i>
                <span>友链</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/blog/images/bg.jpg') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Ajax"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2023-06-17 08:00" pubdate>
          2023年06月17日
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          8.5k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          71 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Ajax</h1>
            
            
              <div class="markdown-body">
                
                <h1 id="Ajax"><a href="#Ajax" class="headerlink" title="Ajax"></a>Ajax</h1><p>Ajax诞生之前：在Ajax出现之前，JS没有原生的直接方法发送异步请求，早期互联网应用网页与服务器之间的通信通常是通过同步请求实现的。同步请求会导致整个页面在等待服务器响应时被冻结，用户无法进行其他操作，体验极差。</p>
<p>但也不是完全没有办法实现异步通信，有一些婉转的实现异步通信的方法，比如</p>
<ol>
<li>隐藏的帧： 将一个隐藏的 <code>&lt;iframe&gt;</code> 元素的源指向服务器资源，通过这个 iframe 来发起请求，然后使用 JavaScript 监听 iframe 的加载事件，从而模拟异步请求。但是这种方法并不常用，也不够灵活。</li>
<li><strong>定时器轮询（Polling with Timers）：</strong> 在 JavaScript 中使用定时器周期性地发起<strong>同步请求</strong>（请求是同步的，意味着仍然会阻塞其他的代码），模拟异步请求的效果。这种方式的缺点是，需要不断地轮询服务器，可能导致不必要的网络开销。</li>
</ol>
<p>而真正的异步通信-Ajax意味着请求发送后立即继续执行后续代码，直到响应返回时执行相应的回调函数。这种方法更加高效、实时，并且减轻了服务器的压力。</p>
<p>Ajax全称是：Asynchronous JavaScript And XML，翻译过来就是“异步的 Javascript 和 XML”。</p>
<blockquote>
<p>Ajax 是一个技术统称，是一个概念模型，它囊括了很多技术，并不特指某一技术，它很重要的特性之一就是让页面实现局部刷新。</p>
</blockquote>
<p>特点：<strong>局部刷新页面</strong>，无需重载整个页面。</p>
<p>简单来说，Ajax 是一种<strong>思想</strong>，XMLHttpRequest 只是实现 Ajax 的一种方式。其中 XMLHttpRequest 模块就是实现 Ajax 的一种很好的方式，这也是很多面试官喜欢让面试者手撕的代码之一。</p>
<p>利用 XMLHttpRequest 模块实现 Ajax。</p>
<h2 id="Ajax发送get请求"><a href="#Ajax发送get请求" class="headerlink" title="Ajax发送get请求"></a>Ajax发送get请求</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs js">&lt;script&gt;<br>    <span class="hljs-comment">// 绑定事件</span><br>    btn.<span class="hljs-property">onclick</span> = <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)&#123;<br>    	<span class="hljs-comment">// 1.创建对象</span><br>    	<span class="hljs-keyword">const</span> xhr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">XMLHttpRequest</span>()<br>        <span class="hljs-comment">// 2.初始化，设置请求方法和url</span><br>        xhr.<span class="hljs-title function_">open</span>(<span class="hljs-string">&#x27;GET&#x27;</span>,<span class="hljs-string">&#x27;http://127.0.0.1:8000/server&#x27;</span>) <span class="hljs-comment">// 如果要加参数url后面跟？a=100&amp;b=200</span><br>    	<span class="hljs-comment">// 3.发送</span><br>    	xhr.<span class="hljs-title function_">send</span>()<br>    	<span class="hljs-comment">// 4. 处理服务器返回的结果</span><br>        <span class="hljs-comment">// 当xhr的readyState属性改变都会触发onreadystatechange事件，而readyState表示当前处在请求/响应的哪个状态</span><br>    	xhr.<span class="hljs-property">onreadystatechange</span> = <span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) &#123;<br>            <span class="hljs-comment">// 异步回调函数</span><br>            <span class="hljs-keyword">if</span> (xhr.<span class="hljs-property">readyState</span> === <span class="hljs-number">4</span>) &#123;<br>                <span class="hljs-keyword">if</span> (xhr.<span class="hljs-property">status</span> === <span class="hljs-number">200</span>) &#123;<br>                    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">info</span>(<span class="hljs-string">&quot;响应结果&quot;</span>, xhr.<span class="hljs-property">response</span>)<br>                &#125;<br>            &#125;<br>        &#125;<br>	&#125;	<br>&lt;/script&gt;  <br></code></pre></td></tr></table></figure>

<h2 id="Ajax发送post请求"><a href="#Ajax发送post请求" class="headerlink" title="Ajax发送post请求"></a>Ajax发送post请求</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs js">&lt;script&gt;<br>    <span class="hljs-comment">// 获取元素对象</span><br>    <span class="hljs-keyword">const</span> result = <span class="hljs-variable language_">document</span>.<span class="hljs-title function_">getElementById</span>(<span class="hljs-string">&#x27;result&#x27;</span>)<br>	<span class="hljs-comment">// 绑定事件</span><br>	result.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">&#x27;mouseover&#x27;</span>,<span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)&#123;<br>        <span class="hljs-comment">// 1.创建对象</span><br>        <span class="hljs-keyword">const</span> xhr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">XMLHttpRequest</span>()<br>        <span class="hljs-comment">// 2.初始化，设置类型与URL</span><br>        xhr.<span class="hljs-title function_">open</span>(<span class="hljs-string">&#x27;POST&#x27;</span>,<span class="hljs-string">&#x27;http://127.0.0.1:8000/server&#x27;</span>)<br>        <span class="hljs-comment">// 3.发送</span><br>        xhr.<span class="hljs-title function_">send</span>()<br>        <span class="hljs-comment">// 4.事件绑定</span><br>        xhr.<span class="hljs-property">onreadystatechange</span> = <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)&#123;<br>            <span class="hljs-comment">// 判断</span><br>            <span class="hljs-keyword">if</span>(xhr.<span class="hljs-property">readyState</span> === <span class="hljs-number">4</span>)&#123;<br>                <span class="hljs-keyword">if</span>(xhr.<span class="hljs-property">status</span> &gt;= <span class="hljs-number">200</span> &amp;&amp; xhr.<span class="hljs-property">status</span> &lt; <span class="hljs-number">300</span>)&#123;<br>                    <span class="hljs-comment">// 处理服务器端返回的结果</span><br>                    result.<span class="hljs-property">innerHTML</span> = xhr.<span class="hljs-property">response</span><br>                &#125;<br>            &#125;<br>        &#125;<br>    &#125;)<br>&lt;/script&gt;  <br></code></pre></td></tr></table></figure>

<p>如果要加参数放在请求体里，多种格式可以用</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 3. 发送</span><br><span class="hljs-comment">// xhr.send(&#x27;a=100&amp;b=200&amp;c=300&#x27;)</span><br><span class="hljs-comment">// xhr.send(&#x27;a:100&amp;b:200&amp;c:300&#x27;)</span><br>xhr.<span class="hljs-title function_">send</span>(<span class="hljs-string">&#x27;124244&#x27;</span>)<br></code></pre></td></tr></table></figure>

<blockquote>
<p><strong>注意：</strong> 我们使用这种方式实现网络请求时，如果请求内部又包含请求，以此循环，就会出现回调地狱，这也是一个诟病，后来才催生了更加优雅的请求方式。</p>
</blockquote>
<h1 id="Fetch"><a href="#Fetch" class="headerlink" title="Fetch"></a>Fetch</h1><p>Fetch 是在 ES6 出现的，它使用了 ES6 提出的 promise 对象， 是一个基于 promise 的浏览器原生就支持的 API。</p>
<blockquote>
<p>不是对XMLHttpRequest的封装，是一种新的获取资源的接口方式。</p>
</blockquote>
<p><strong>特点：</strong></p>
<ul>
<li>使用 promise，不使用回调函数。</li>
<li>采用模块化设计，比如 rep、res 等对象分散开来，比较友好。</li>
<li>通过数据流对象处理数据，可以提高网站性能。</li>
</ul>
<p>Fetch 实现网络请求</p>
<ul>
<li>参数：resource、config</li>
<li>返回结果：值为Response对象的Promise</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs js">&lt;body&gt;<br>  <span class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="language-javascript"><span class="language-xml">    <span class="hljs-keyword">function</span> <span class="hljs-title function_">ajaxFetch</span>(<span class="hljs-params">url</span>) &#123;</span></span><br><span class="language-javascript"><span class="language-xml">      <span class="hljs-title function_">fetch</span>(url).<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> res.<span class="hljs-title function_">json</span>()).<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> &#123;</span></span><br><span class="language-javascript"><span class="language-xml">          <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">info</span>(data)</span></span><br><span class="language-javascript"><span class="language-xml">      &#125;)</span></span><br><span class="language-javascript"><span class="language-xml">    &#125;</span></span><br><span class="language-javascript"><span class="language-xml">    <span class="hljs-title function_">ajaxFetch</span>(<span class="hljs-string">&#x27;https://smallpig.site/api/category/getCategory&#x27;</span>)</span></span><br><span class="language-javascript"><span class="language-xml">  </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span><br>&lt;/body&gt;<br></code></pre></td></tr></table></figure>

<blockquote>
<p>上段代码利用 Fetch 发送了一个最简单的 get 请求，其中最重要的特点之一就是采用了.then 链式调用的方式处理结果，这样不仅利于代码的可读，而且也解决了回调地狱的问题。</p>
</blockquote>
<h1 id="Fetch-VS-XMLHttpRequest"><a href="#Fetch-VS-XMLHttpRequest" class="headerlink" title="Fetch VS XMLHttpRequest"></a>Fetch VS XMLHttpRequest</h1><ul>
<li><p>请求</p>
<p>从发请求的接口参数开始看</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-title function_">fetch</span>( <span class="hljs-string">&#x27;/v1/accounts&#x27;</span>, &#123;<br>  <span class="hljs-attr">method</span>:    <span class="hljs-comment">// 发送方式</span><br>  <span class="hljs-attr">headers</span>:   <span class="hljs-comment">// 请求头</span><br>  <span class="hljs-attr">body</span>:      <span class="hljs-comment">// 请求体（请求所携带的参数）</span><br>  <span class="hljs-attr">credentials</span>: <span class="hljs-comment">// 控制请求是否带上 cookie 等机密信息</span><br>  <span class="hljs-attr">mode</span>:        <span class="hljs-comment">// 设置请求方式的标志位</span><br>  cache：<br>  <span class="hljs-attr">redirect</span>:<br>  <span class="hljs-attr">referrer</span>:<br>  <span class="hljs-attr">referrerPolicy</span>:<br>  <span class="hljs-attr">integrity</span>:<br>&#125; )<br></code></pre></td></tr></table></figure>

<ol>
<li><p>credentials</p>
<p>控制请求是否带上 cookie 等机密信息。fetch 可接收如下三种值：</p>
<ul>
<li>omit: 请求不带任何 cookie。</li>
<li>same-origin: 同域请求会带上 cookie。</li>
<li>include: 无论是否跨域都会带上 cookie。</li>
</ul>
<p>XMLHttpRequest 对应也有一个 withCredentials 标志位对应此参数，withCredentials 只有两个取值：</p>
<ul>
<li>true: 大致对应上面的 include，MDN 上描述此 flag 不止控制 cookie 还控制 authorization headers 或者 TLS client certificates。</li>
<li>false: 大致对应上面的 omit，MDN 上描述为 false 时还控制跨域请求的 response 不能设置 cookie。</li>
</ul>
</li>
<li><p>mode</p>
<p>设置请求方式的标志位。fetch 可以通过设置这个标志位从发起请求阶段就阻止跨域请求。</p>
<p><strong>而 XMLHttpRequest 并没有对应的标志位</strong>，只能先发出请求然后通过检测 response 头中是否有允许跨域的字段来判断是否要阻止接收 response。</p>
</li>
<li><p>redirect</p>
<p>设置请求如果遇到重定向的返回如何响应：</p>
<ul>
<li>follow: 跟随重定向</li>
<li>error: 如果 response 是重定向，则报错</li>
<li>manual: 自定义行为</li>
</ul>
<p><strong>XMLHttpRequest 没有对应的字段</strong>。</p>
</li>
</ol>
</li>
<li><p>响应</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-title function_">fetch</span>( url, option ).<span class="hljs-title function_">then</span>( <span class="hljs-keyword">function</span>(<span class="hljs-params">response</span>)&#123;<br>  response.<span class="hljs-property">headers</span>  <br>  response.<span class="hljs-property">ok</span>          <span class="hljs-comment">// 请求成功,XHLHttpRequest 没有对应的字段。</span><br>  response.<span class="hljs-property">status</span><br>  response.<span class="hljs-property">statusText</span><br>  response.<span class="hljs-property">redirected</span>  <span class="hljs-comment">// 此标志位表示请求是否被重定向了。XMLHttpRequest 没有对应的字段。</span><br>  response.<span class="hljs-property">type</span>        <span class="hljs-comment">// 表示 response 的类型，XMLHttpRequest 没有对应的字段。</span><br>  response.<span class="hljs-property">url</span><br>  response.<span class="hljs-title function_">arrayBuffer</span>()<br>  response.<span class="hljs-title function_">blob</span>()<br>  response.<span class="hljs-title function_">formData</span>()<br>  response.<span class="hljs-title function_">json</span>()<br>  response.<span class="hljs-title function_">text</span>()<br>&#125; )<br></code></pre></td></tr></table></figure></li>
</ul>
<p>总的来说，fetch API 提供了对请求更精确的控制。对 cookie，对跨域等功能都有了传统 Ajax（XMLHttpRequest）没有的功能，响应（response）还提供了一些的原来没有的标志位。</p>
<h1 id="Axios"><a href="#Axios" class="headerlink" title="Axios"></a>Axios</h1><blockquote>
<p>Axios 是一个基于 promise 封装的ajax请求库，可以用在浏览器和 node.js 中。</p>
<p>实际上，axios可以用在浏览器和 node.js 中是因为，它会自动判断当前环境是什么，如果是浏览器，就会基于XMLHttpRequests实现axios。如果是node.js环境，就会基于node内置核心模块http实现axios。</p>
</blockquote>
<h2 id="特点"><a href="#特点" class="headerlink" title="特点"></a>特点</h2><ul>
<li>从浏览器中创建 XMLHttpRequests</li>
<li>从 node.js 创建 http 请求</li>
<li>支持 Promise API</li>
<li>拦截请求和响应</li>
<li>转换请求数据和响应数据</li>
<li>取消请求</li>
<li>自动转换 JSON 数据</li>
<li>客户端支持防御 XSRF</li>
</ul>
<h2 id="支持多种请求方式"><a href="#支持多种请求方式" class="headerlink" title="支持多种请求方式"></a>支持多种请求方式</h2><ul>
<li>axios(config)</li>
<li>axios.request(config)</li>
<li>axios.get(ur[,config])</li>
<li>axios.delete(ur[,config])</li>
<li>axios.head(url[,config])</li>
<li>axios.post(url[,data[,config]])</li>
<li>axios.put(url[,data[,config]])</li>
<li>axios.patch(url[,data[,config]])</li>
</ul>
<h2 id="axios基本使用"><a href="#axios基本使用" class="headerlink" title="axios基本使用"></a>axios基本使用</h2><ul>
<li>默认是get请求</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-title function_">axios</span>(&#123;<br>  <span class="hljs-attr">url</span>:<span class="hljs-string">&#x27;http://123.207.32.32:8000/home/multidata&#x27;</span>,<br>    <span class="hljs-comment">//method:&#x27;post&#x27;</span><br>&#125;).<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span>&#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(res);<br>&#125;)<br></code></pre></td></tr></table></figure>

<ul>
<li>get携带参数写法</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">//法一、直接放入url用?连接参数</span><br><span class="hljs-title function_">axios</span>(&#123;<br>  <span class="hljs-attr">url</span>:<span class="hljs-string">&#x27;http://123.207.32.32:8000/home/data?type=sell&amp;page=3&#x27;</span><br>&#125;).<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span>&#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(res);<br>&#125;)<br><span class="hljs-comment">//法二、用params传参</span><br><span class="hljs-title function_">axios</span>(&#123;<br>  <span class="hljs-attr">url</span>:<span class="hljs-string">&#x27;http://123.207.32.32:8000/home/data&#x27;</span>,<br>  <span class="hljs-attr">params</span>:&#123;<br>      <span class="hljs-attr">type</span>:<span class="hljs-string">&#x27;pop&#x27;</span>,<br>      <span class="hljs-attr">page</span>:<span class="hljs-number">1</span><br>  &#125;<br>&#125;).<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span>&#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(res);<br>&#125;)<br></code></pre></td></tr></table></figure>

<ul>
<li>axios发送并发请求</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">//类似promise的all</span><br>axios.<span class="hljs-title function_">all</span>([<br>  <span class="hljs-title function_">axios</span>(&#123;<br>    <span class="hljs-attr">url</span>:<span class="hljs-string">&#x27;http://123.207.32.32:8000/home/multidata&#x27;</span><br>  &#125;),<br>  <span class="hljs-title function_">axios</span>(&#123;<br>    <span class="hljs-attr">url</span>:<span class="hljs-string">&#x27;http://123.207.32.32:8000/home/data&#x27;</span>,<br>    <span class="hljs-attr">params</span>:&#123;<br>      <span class="hljs-attr">type</span>:<span class="hljs-string">&#x27;sell&#x27;</span>,<br>      <span class="hljs-attr">page</span>:<span class="hljs-number">5</span><br>    &#125;<br>  &#125;)<br>]).<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">results</span> =&gt;</span>&#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(results);<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(results[<span class="hljs-number">0</span>]);<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(results[<span class="hljs-number">1</span>]);<br>&#125;)<br></code></pre></td></tr></table></figure>

<h2 id="常见全局配置"><a href="#常见全局配置" class="headerlink" title="常见全局配置"></a>常见全局配置</h2><ul>
<li><code>axios.defaults.+配置信息</code>可以拿到axios的配置信息</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">//使用全局axios提取全局的配置</span><br>axios.<span class="hljs-property">defaults</span>.<span class="hljs-property">baseURL</span> = <span class="hljs-string">&#x27;http://123.207.32.32:8000&#x27;</span><br><span class="hljs-comment">//发送并发请求</span><br>axios.<span class="hljs-title function_">all</span>([<br>  <span class="hljs-title function_">axios</span>(&#123;<br>    <span class="hljs-attr">url</span>:<span class="hljs-string">&#x27;/multidata&#x27;</span><br>  &#125;),<br>  <span class="hljs-title function_">axios</span>(&#123;<br>    <span class="hljs-attr">url</span>:<span class="hljs-string">&#x27;/home/data&#x27;</span>,<br>    <span class="hljs-attr">params</span>:&#123;<br>      <span class="hljs-attr">type</span>:<span class="hljs-string">&#x27;sell&#x27;</span>,<br>      <span class="hljs-attr">page</span>:<span class="hljs-number">5</span><br>    &#125;<br>  &#125;)<br>]).<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">results</span> =&gt;</span>&#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(results);<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(results[<span class="hljs-number">0</span>]);<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(results[<span class="hljs-number">1</span>]);<br>&#125;)<br></code></pre></td></tr></table></figure>

<ul>
<li>axios常见配置（config）</li>
</ul>
<p><img src="" srcset="/blog/img/loading.gif" lazyload data-original="https://markdown-1307246189.cos.ap-chongqing.myqcloud.com/%20markdown/image-20230616104425111.png" alt="image-20230616104425111"></p>
<h2 id="axios实例和模块封装"><a href="#axios实例和模块封装" class="headerlink" title="axios实例和模块封装"></a>axios实例和模块封装</h2><p>为什么要封装axios？</p>
<ol>
<li>当一个库不维护时，便于在封装的地方把不维护的库替换掉。</li>
<li>可以进行一些统一配置处理，例如设置请求的超时时间、设置请求头部信息、处理请求错误等。这样可以确保在整个项目中使用相同的配置，并且在需要修改配置时只需要在封装的地方进行修改，而不需要逐个地修改每个请求的代码。</li>
<li>可以进行拦截器的统一处理，在拦截器中添加公共的逻辑。例如在请求中添加认证信息、处理请求错误、统一处理响应等。</li>
<li>可以将不同的请求逻辑封装成不同的函数或模块，方便复用和维护。可以共享一些请求逻辑。提高代码的可读性和可维护性。</li>
</ol>
<ul>
<li>axios实例</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> instance1 = axios.<span class="hljs-title function_">create</span>(&#123;<br>  <span class="hljs-attr">baseURL</span>:<span class="hljs-string">&#x27;http://123.207.32.32:8000&#x27;</span>,<br>  <span class="hljs-attr">timeout</span>:<span class="hljs-number">5000</span><br>&#125;)<br><br><span class="hljs-title function_">instance1</span>(&#123;<br>  <span class="hljs-attr">url</span>:<span class="hljs-string">&#x27;/home/multidata&#x27;</span><br>&#125;).<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span>&#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(res);<br>&#125;)<br></code></pre></td></tr></table></figure>

<ul>
<li><p>封装request模块</p>
<ul>
<li>方法一</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">//在network文件夹下新建request.js</span><br><span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;axios&#x27;</span><br><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">request</span>(<span class="hljs-params">config,success,failure</span>)&#123;<br>    <span class="hljs-comment">//1.创建axios的实例</span><br>    <span class="hljs-keyword">const</span> instance = axios.<span class="hljs-title function_">create</span>(&#123;<br>        <span class="hljs-attr">baseURL</span>:<span class="hljs-string">&#x27;http://123.207.32.32:8000&#x27;</span>,<br>        <span class="hljs-attr">timeout</span>:<span class="hljs-number">5000</span><br>    &#125;)<br>    <span class="hljs-comment">//2.发送真正的网络请求</span><br>    <span class="hljs-title function_">instance</span>(config)<br>    .<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">res</span>=&gt;</span>&#123;<br>        <span class="hljs-title function_">success</span>(res)<br>    &#125;)<br>    .<span class="hljs-title function_">catch</span>(<span class="hljs-params">err=&gt;</span>)&#123;<br>        <span class="hljs-title function_">failure</span>(err)<br>    &#125;<br>&#125;<br><br><span class="hljs-comment">//在使用处</span><br><span class="hljs-keyword">import</span> request <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;../network/request.js&#x27;</span><br><br><span class="hljs-title function_">request</span>(&#123;<br>    <span class="hljs-attr">url</span>:<span class="hljs-string">&#x27;.home/multidata&#x27;</span><br>&#125;,<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span>&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(res)<br>&#125;,<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span>&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(err) <br>&#125;)<br></code></pre></td></tr></table></figure>

<ul>
<li>方法二</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">//在network文件夹下新建request.js</span><br><span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;axios&#x27;</span><br><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">request</span>(<span class="hljs-params">config</span>)&#123;<br>    <span class="hljs-comment">//1.创建axios的实例</span><br>    <span class="hljs-keyword">const</span> instance = axios.<span class="hljs-title function_">create</span>(&#123;<br>        <span class="hljs-attr">baseURL</span>:<span class="hljs-string">&#x27;http://123.207.32.32:8000&#x27;</span>,<br>        <span class="hljs-attr">timeout</span>:<span class="hljs-number">5000</span><br>    &#125;)<br>    <span class="hljs-comment">//2.发送真正的网络请求</span><br>    <span class="hljs-title function_">instance</span>(config.<span class="hljs-property">baseConfig</span>)<br>    .<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">res</span>=&gt;</span>&#123;<br>        config.<span class="hljs-title function_">success</span>(res)<br>    &#125;)<br>    .<span class="hljs-title function_">catch</span>(<span class="hljs-params">err=&gt;</span>)&#123;<br>        config.<span class="hljs-title function_">failure</span>(err)<br>    &#125;<br>&#125;<br><br><span class="hljs-comment">//在使用处</span><br><span class="hljs-keyword">import</span> request <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;../network/request.js&#x27;</span><br><br><span class="hljs-title function_">request</span>(&#123;<br>    <span class="hljs-attr">baseConfig</span>:&#123;&#125;,<br>    <span class="hljs-attr">success</span>:<span class="hljs-keyword">function</span>(<span class="hljs-params">res</span>)&#123;&#125;,<br>    <span class="hljs-attr">failure</span>:<span class="hljs-keyword">function</span>(<span class="hljs-params">err</span>)&#123;&#125;,<br>&#125;)<br></code></pre></td></tr></table></figure>

<ul>
<li>&#x3D;&#x3D;方法三&#x3D;&#x3D;Promise写法</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">//在network文件夹下新建request.js</span><br><span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;axios&#x27;</span><br><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">request</span>(<span class="hljs-params">config</span>)&#123;<br>        <span class="hljs-comment">//1.创建axios的实例</span><br>        <span class="hljs-keyword">const</span> instance = axios.<span class="hljs-title function_">create</span>(&#123;<br>            <span class="hljs-attr">baseURL</span>:<span class="hljs-string">&#x27;http://123.207.32.32:8000&#x27;</span>,<br>            <span class="hljs-attr">timeout</span>:<span class="hljs-number">5000</span><br>        &#125;)<br>         <span class="hljs-comment">//2.axios的拦截器(如果要拦截请求或响应做额外的操作)</span><br>        <span class="hljs-comment">//2.1请求拦截</span><br>        instance.<span class="hljs-property">interceptors</span>.<span class="hljs-property">request</span>.<span class="hljs-title function_">use</span>(<span class="hljs-function"><span class="hljs-params">config</span> =&gt;</span>&#123;<br>            <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(config)<span class="hljs-comment">//可以对config作处理，比如config中的一些信息不符合服务器的要求，比如每次发送网络请求时，都希望在界面中显示一个请求的图标，比如每次发送网络请求时，都希望在界面中显示一个请求的图标。</span><br>            <span class="hljs-keyword">return</span> config<br>        &#125;,<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span>&#123;<br>            <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(err)<br>        &#125;)<br>        <span class="hljs-comment">//2.2响应拦截</span><br>        instance.<span class="hljs-property">interceptors</span>.<span class="hljs-property">response</span>.<span class="hljs-title function_">use</span>(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span>&#123;<br>            <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(res)<br>            <span class="hljs-keyword">return</span> res.<span class="hljs-property">data</span><br>        &#125;,<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span>&#123;<br>            <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(err)<br>        &#125;<br>        <br>        <span class="hljs-comment">//3.发送真正的网络请求</span><br>        <span class="hljs-keyword">return</span> <span class="hljs-title function_">instance</span>(config) <br>&#125;<br><br><span class="hljs-comment">//在使用处</span><br><span class="hljs-keyword">import</span> request <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;../network/request.js&#x27;</span><br><br><span class="hljs-title function_">request</span>(&#123;<br>    <span class="hljs-attr">url</span>:<span class="hljs-string">&#x27;/home/multidata&#x27;</span><br>&#125;).<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">res</span>=&gt;</span>&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(res);<br>&#125;).<span class="hljs-title function_">catch</span>(<span class="hljs-function"><span class="hljs-params">err</span>=&gt;</span>&#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(err)<br>&#125;)<br></code></pre></td></tr></table></figure>
<ul>
<li><p>配置优先级</p>
<blockquote>
<p>配置项通过一定的规则合并，request config &gt; instance.defaults &gt; 系统默认，优先级高的覆盖优先级低的。</p>
</blockquote>
</li>
</ul>
</li>
</ul>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><ul>
<li>Ajax，异步的JavaScript和XML，是js里的一种异步思想，具体而言就是可以局部刷新页面，无需重载整个页面。</li>
<li>XMLHttpRequest ，早期实现 Ajax 的方式主要是用xhr实现的。现在流行的一些网络请求三方库也是基于xhr的二次封装，比如我们常用的axios。</li>
<li>fetch使用了 ES6 提出的 promise 对象，是一种新的获取资源的接口方式，是一个浏览器原生就支持的api。</li>
<li>axios是一个基于 promise 对原生 Ajax 封装的 HTTP 库，可以用在浏览器和 node.js 中。是用于网络请求的第三方库，需要引入，浏览器原生不支持。</li>
</ul>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/blog/categories/%E5%89%8D%E7%AB%AF%E6%8A%80%E6%9C%AF%E6%A0%88/" class="category-chain-item">前端技术栈</a>
  
  
    <span>></span>
    
  <a href="/blog/categories/%E5%89%8D%E7%AB%AF%E6%8A%80%E6%9C%AF%E6%A0%88/js/" class="category-chain-item">js</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Ajax</div>
      <div>https://airfe.gitee.io/blog/2023/06/17/Ajax/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>Airfe</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2023年6月17日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/blog/2023/06/19/Axios%E9%83%A8%E5%88%86%E6%BA%90%E7%A0%81%E8%A7%A3%E8%AF%BB/" title="Axios部分源码解读">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Axios部分源码解读</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/blog/2023/06/13/%E7%BD%91%E9%A1%B5%E5%B8%83%E5%B1%80%E6%96%B9%E5%BC%8F/" title="网页布局方式">
                        <span class="hidden-mobile">网页布局方式</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
  
  
    <article id="comments" lazyload>
      
  <div id="valine"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#valine', function() {
      Fluid.utils.createScript('https://lib.baomitu.com/valine/1.5.1/Valine.min.js', function() {
        var options = Object.assign(
          {"appId":"RW68dMkEpeIOJJiBr1lPkhOS-gzGzoHsz","appKey":"P5fzMTGSJIoTaGvmgzsUHeNZ","path":"window.location.pathname","placeholder":"发表你的看法吧~","avatar":"retro","meta":["nick","mail","link"],"requiredFields":[],"pageSize":10,"lang":"zh-CN","highlight":false,"recordIP":false,"serverURLs":"","emojiCDN":null,"emojiMaps":null,"enableQQ":false,"appid":"RW68dMkEpeIOJJiBr1lPkhOS-gzGzoHsz","appkey":"P5fzMTGSJIoTaGvmgzsUHeNZ","server_url":"https://rw68dmke.lc-cn-n1-shared.com"},
          {
            el: "#valine",
            path: window.location.pathname
          }
        )
        new Valine(options);
        Fluid.utils.waitElementVisible('#valine .vcontent', () => {
          var imgSelector = '#valine .vcontent img:not(.vemoji)';
          Fluid.plugins.imageCaption(imgSelector);
          Fluid.plugins.fancyBox(imgSelector);
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


    </article>
  


          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
        <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> <div style="font-size: 0.85rem"> <span id="timeDate">载入天数</span> <span id="times">载入时分秒</span> <script src="js/duration.js"></script> </div> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="leancloud-site-pv-container" style="display: none">
        总访问量 
        <span id="leancloud-site-pv"></span>
         次
      </span>
    
    
      <span id="leancloud-site-uv-container" style="display: none">
        总访客数 
        <span id="leancloud-site-uv"></span>
         人
      </span>
    
    

  
</div>

  
  
    <!-- 备案信息 ICP for China -->
    <div class="beian">
  <span>
    <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
      蜀ICP备2023008943号
    </a>
  </span>
  
    
      <span>
        <a
          href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=https://beian.miit.gov.cn/"
          rel="nofollow noopener"
          class="beian-police"
          target="_blank"
        >
          
            <span style="visibility: hidden; width: 0">|</span>
            <img src="" srcset="/blog/img/loading.gif" lazyload data-original="/blog/img/police_beian.png" alt="police-icon"/>
          
          <span>京公网安备12345678号</span>
        </a>
      </span>
    
  
</div>

  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/blog/js/events.js" ></script>
<script  src="/blog/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/blog/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script defer src="/blog/js/leancloud.js" ></script>

  <script  src="/blog/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/blog/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>

        <style>
            [bg-lazy] {
                background-image: none !important;
                background-color: #eee !important;
            }
        </style>
        <script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(r){r.imageLazyLoadSetting.processImages=t;var e=r.imageLazyLoadSetting.isSPA,n=r.imageLazyLoadSetting.preloadRatio||1,c=a();function a(){var t=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")),e=Array.prototype.slice.call(document.querySelectorAll("[bg-lazy]"));return t.concat(e)}function t(){e&&(c=a());for(var t,o=0;o<c.length;o++)0<=(t=(t=c[o]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(r.innerHeight*n||document.documentElement.clientHeight*n)&&function(){var t,e,n,a,i=c[o];e=function(){c=c.filter(function(t){return i!==t}),r.imageLazyLoadSetting.onImageLoaded&&r.imageLazyLoadSetting.onImageLoaded(i)},(t=i).hasAttribute("bg-lazy")?(t.removeAttribute("bg-lazy"),e&&e()):(n=new Image,a=t.getAttribute("data-original"),n.onload=function(){t.src=a,t.removeAttribute("data-original"),e&&e()},t.src!==a&&(n.src=a))}()}function i(){clearTimeout(t.tId),t.tId=setTimeout(t,500)}t(),document.addEventListener("scroll",i),r.addEventListener("resize",i),r.addEventListener("orientationchange",i)}(this);</script></body>
</html>
